#!/usr/bin/perl -w 

########
# Caller v.2.1 Odessa edition
# Using databases
#######

use strict;
use Class::Date qw(date);
use Data::Dump qw(dump);

use Proc::Daemon;
use Proc::PID::File;

use DBI;

use vars '$config';

my $params = shift;

# Читаем конфигурационный файл
$config = sys_read_config("/scripts/caller/caller.conf");

sub sys_read_config {
    my ( $configfile ) = @_;
    my ($conf,$line,$section);
    open (CONFIGFILE, $configfile) or return 0;
    $conf->{'_filename'} = $configfile;
    while ($line = <CONFIGFILE>) {
        if ($line =~ /^\[(.*)\]/) {
    	    $section = $1;
        } elsif ($line =~ /^[\ \t]*([^=\ \t]+)[\ \t]*=[\ \t]*(.*)[\ \t]*/) {
    	    my ($config_name, $config_val) = ($1, $2);
            if ($section) {
        	$conf->{"$section.$config_name"} = $config_val;
    	    } else {
    		$conf->{$config_name} = $config_val;
    	    }
        }                           
    }
    close CONFIGFILE;
    return $conf;
}

# Выполняем запросы
sub execute {
    my ($sql) = @_;
    my (@result, $dbh, $sth, $rv);
    
    $dbh = DBI->connect("dbi:Pg:dbname=".$config->{"base.name"}.";host=".$config->{"base.host"}.";port=".$config->{"base.port"},
	    $config->{"base.username"},
	    $config->{"base.password"}, 
	    {PrintError => 0});

    $sth = $dbh->prepare($sql);
    $rv = $sth->execute();

    while(my @row = $sth->fetchrow_array()) {
    	push(@result, [@row]);
    }

    $sth->finish();
    $dbh->disconnect();    
    
    return @result;
}


# Создаем Для каждого телефонного номера файл для звонка Астериска
sub make_outgoing_file {

	my ( $id, $number, $prefix, $callerid, $max_retries, $retry_time, $wait_time, $context, $pro_id ) = @_;

	execute ("UPDATE odessa.caller_phones SET pho_count=pho_count+1, pho_done=-1 WHERE pho_id=$id");

	open(OUTFILE, ">/tmp/".$id);
	print OUTFILE ("Channel: ".$prefix.$number."\n");
	print OUTFILE ("\n");
	print OUTFILE ("Callerid: ".$callerid."\n");
	print OUTFILE ("\n");
	print OUTFILE ("MaxRetries: ".$max_retries."\n");
	print OUTFILE ("RetryTime: ".$retry_time."\n");
	print OUTFILE ("WaitTime: ".$wait_time."\n");
	print OUTFILE ("\n");
	print OUTFILE ("Context: ".$context."\n");
	print OUTFILE ("Extension: ".$id."\n");
	print OUTFILE ("\n");
	print OUTFILE ("Setvar: var_number=".$number."\n");
	print OUTFILE ("Setvar: var_id=".$id."\n");
	print OUTFILE ("Setvar: var_pro_id=".$pro_id."\n");
	print OUTFILE ("Setvar: var_time=".time()."\n");
	print OUTFILE ("\n");
	print OUTFILE ("Priority: 1\n");
#	print OUTFILE ("\n");
#	print OUTFILE ("Archive: yes\n");
	close(OUTFILE);
	
	system("mv /tmp/".$id." ".$config->{"main.outgoing_path"}."/".$id);
}


MAIN:
{
# Инициализация даймона
    Proc::Daemon::Init();

    if (Proc::PID::File->running()) {
        exit(0);
    }
    
    
    for (;;) {


## проверяем директорию outgoing
	chdir $config->{"main.outgoing_path"};
	my @files = <*>;
	my $count_files = scalar(@files);
	my $free_channels = $config->{"main.channel_limit"}-$count_files;
	
## делаем запрос по недостающему количеству файлов
    my $date = date(time());
    if($config->{"main.forbid_begin"} > $date->hour && $config->{"main.forbid_end"} <= $date->hour) {
	my @phones = execute ("
	    SELECT * FROM odessa.caller_phones ph
	     JOIN caller_project pr ON (ph.pro_id=pr.pro_id)
	     JOIN caller_project_time pt ON (pt.pro_id=pr.pro_id)
	    WHERE (ph.pho_done=0)
	     AND (EXTRACT(DOW FROM NOW())=pt.prt_dow)
	     AND (NOW() BETWEEN pr.pro_date_begin AND pr.pro_date_end)
	     AND (current_time BETWEEN pt.prt_time_begin AND pt.prt_time_end)
	     AND ph.pho_count<pr.pro_total_max_retries
	    ORDER BY ph.pho_count ASC, RANDOM()
	    LIMIT $free_channels
	");
	
## на каждую строчку - готовим и переносим файл в outgoing
	foreach my $phone (@phones) {
	    make_outgoing_file($phone->[0],$phone->[2],$phone->[9],$phone->[10],$phone->[11],$phone->[14],$phone->[13],$phone->[15],$phone->[1]);
	}
    }

=c u t	
## читаем результат из outgoing_done
## импортируем результат из sql файла
	chdir $config->{"main.outgoing_done_path"};
	my @donefiles = <*>;
	foreach my $donefile (@donefiles) {
	    my $done = 0;
	    my $figstatus = "";
	    open (DONEFILE, $donefile);
	    while (my $linefile = <DONEFILE>) {
		if ($donefile eq "import.sql"){
		    execute ($linefile);
		} else {
		    if ($linefile =~ /^Status: Completed(.*)/) {
			$done = 1;
		    } elsif ($linefile =~ /^Status: (.*)/) {
			$figstatus = ($1);
		    }
		}
	    }
	    close DONEFILE;
	    system("rm $donefile");
#	    my @phones_done = execute ("SELECT * FROM caller_phones WHERE pho_id=$donefile");
#	    execute ("UPDATE caller_phones SET pho_done=$done WHERE pro_id=".$phones_done[0]->[1]." AND pho_phone='".$phones_done[0]->[2]."'") if ($donefile ne "import.sql");
	    execute ("UPDATE caller_phones SET pho_done=$done WHERE pho_id=$donefile") if ($donefile ne "import.sql");
	    execute ("INSERT INTO caller_results VALUES (DEFAULT, '$donefile', '$figstatus', '".time()."', '".time()."', 0)") if ($figstatus ne "");
	}
=cut	

## ждем чуть-чуть
	sleep ($config->{"main.call_pause"});

    }
    
}

1;
    